console.log('执行app.js')
const express = require("express");
const bodyparser = require("body-parser"); //body中间件
const testsRouter = require("./router/tests.js"); //测试信息路由
const adminRouter = require("./router/admin.js"); //管理菜单等路由
const appCommentRouter = require("./router/appComment.js"); //评论模块路由
const translateRouter = require("./router/translate.js"); //评论模块路由
const feedbackRouter = require("./router/feedback.js"); //评论模块路由
const brandRouter = require("./router/brand.js"); //评论模块路由
const uploadRouter = require("./router/upload.js");
const uploadPackageRouter = require("./router/uploadPackage.js");
const webhookRouter = require("./router/webhook.js");
const reportRouter = require("./router/report.js");
const waRouter = require("./router/wa.js");
const qrCodeRouter = require("./router/qrCode.js");
const beautyRouter = require("./router/beauty.js");
const ainoteRouter = require("./router/ainote.js");
const subscriptionApiHandlerRouter = require("./router/subscriptionApiHandler.js");
const appVersionHandlerRouter = require("./router/appVersion.js");
const appMonitorHandlerRouter = require("./router/appMonitor.js");
const aiDebugHandlerRouter = require("./router/ai_debug.js");
const TransirRouter = require("./router/Transir.js");
const CalorieRouter = require("./router/Calorie.js");
const RecipeRouter = require("./router/Recipe.js");
const iptvRouter = require("./router/iptv.js");
const statisticsRouter = require("./router/statistics.js");
const cors = require("cors"); //解决跨域的中间件 
const server = express();
const path = require("path");
const { errLog } = require("./utils/err");
const utils = require("./utils/index.js");
const startCronJobs = require("./tasks/scheduler");
const cohortRoutes = require('./router/cohortApiRoutes');
// const ws_server = require("./webSocket");
// // 启动 WebSocket 服务
// ws_server.listen(8980, () => {
//     console.log('WebSocket 服务运行在 8980 端口');
// });

// 启动定时任务
startCronJobs();

const utcMs = 1751365137000;
const date = new Date(utcMs);
// toLocaleString 默认会显示本地（如果你系统设置的是中国区域就是自动北京时间）
console.log(date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }));
// 引入 service, scheduler
const AppleSubscriptionStatsService = require('./router/AppleSubscriptionStatsService');
const CronJobScheduler = require('./router/CronJobScheduler');
const AppleSubscriptionStatsServiceMOMO = require('./router/AppleSubscriptionStatsService');
const CronJobSchedulerMOMO = require('./router/CronJobScheduler');
const { startCohortScheduler } = require('./router/dailyCohortTask');
//  startCohortScheduler();
// console.log('⏰ Cohort统计定时任务调度器已启动');
// 1. 先实例化唯一 AppleSubscriptionStatsService（此类只用你pool，不要传dbConfig了！）
const statsService = new AppleSubscriptionStatsService();
const statsServiceMOMO = new AppleSubscriptionStatsServiceMOMO();
// 2. 初始化调度器
const scheduler = new CronJobScheduler(statsService, [
    'com.seamobitech.UniversalTVRemoteControl',
    'com.seamobitech.roku',

    'com.finger.AINoteTaker',
    'com.seamobitech.BeautyAI',
    'com.seamobitech.HeartPulse',
    'com.seamobitech.QRCodeReadAndGenerate',
    'com.seamobitech.whatsscanwebclone',
    'com.zhijian.remoteControl'
]);
const schedulerMOMO = new CronJobSchedulerMOMO(statsServiceMOMO, [
    'com.trans.translationAiAndSubtitle'
]);



// // 2. 启动日常定时任务
// scheduler.startAllJobs();


// // 3. 启动每日统计Cron
// scheduler.startDailyStatsJob();

// 4. 需要手动跑、批量跑，直接用 scheduler 实例上方法
//昨天
// await scheduler.executeManualStats(...);
//历史

async function main() {
    // 需要手动跑、批量跑，直接用 scheduler 实例上方法

    // 1. 首次部署 - 补历史数据
    // await scheduler.executeCompleteHistoricalStats('com.seamobitech.UniversalTVRemoteControl', '2024-09-07', '2025-07-16');
    // await scheduler.executeCompleteHistoricalStats('com.seamobitech.roku', '2024-07-05', '2025-07-16');
    // await scheduler.executeCompleteHistoricalStats('com.seamobitech.whatsscanwebclone', '2024-10-22', '2025-07-21');
    // await scheduler.executeCompleteHistoricalStats('com.finger.AINoteTaker', '2025-05-23', '2025-07-21');
    // await scheduler.executeCompleteHistoricalStats('com.seamobitech.BeautyAI', '2025-01-02', '2025-07-21');
    // await scheduler.executeCompleteHistoricalStats('com.seamobitech.HeartPulse', '2025-02-06', '2025-07-21');
    // await scheduler.executeCompleteHistoricalStats('com.seamobitech.QRCodeReadAndGenerate', '2024-11-25', '2025-07-21');
    // await scheduler.executeCompleteHistoricalStats('com.zhijian.remoteControl', '2025-04-18', '2025-07-20');
    // await scheduler.executeManualConversionStats('com.seamobitech.BeautyAI', '2025-07-17');
    // await scheduler.executeManualConversionStats('com.seamobitech.HeartPulse', '2025-07-17');
    // await scheduler.executeManualConversionStats('com.seamobitech.QRCodeReadAndGenerate', '2025-07-17');
    // await scheduler.executeManualConversionStats('com.zhijian.remoteControl', '2025-07-17');
    // await scheduler.executeManualConversionStats('com.finger.AINoteTaker', '2025-07-17');
    scheduler.startAllJobs();
}
async function main1() {
    // 需要手动跑、批量跑，直接用 scheduler 实例上方法
    // await scheduler.executeCompleteHistoricalStats('com.trans.translationAiAndSubtitle', '2025-06-22', '2025-07-16');
    schedulerMOMO.startAllJobs();
}
if (process?.env?.HOSTNAME?.includes("192-46-226-198")) {
    main();
}
if (process?.env?.HOSTNAME?.includes("iZbp1h1gu3djkpokro224cZ")) {
    main1()
}


server.listen(5000);

// 调整 JSON 请求体限制 (示例设置为 50MB)
server.use(express.json({ limit: '500mb' }));

// 调整 URL-encoded 请求体限制 (如果使用)
server.use(express.urlencoded({ limit: '500mb', extended: true }));
server.use(cors({ origin: "*" }));
server.use(express.static("./public")); //用户的静态资源
server.use(bodyparser.json());
// 提供静态文件服务，让上传的文件可以被访问到
server.use(
    "/home/wwwroot/default/node-server/files",
    express.static("/home/wwwroot/default/node-server/files")
);

server.use(
    bodyparser.urlencoded({
        //body中间件
        extended: false,
    })
);
server.use(async function (req, res, next) {
    //   if (req.headers.token) {
    //     let user = await utils.getUserInfo(req, res);
    //     if (user.status === 0)
    //       return res.send(
    //         utils.returnData({
    //           code: 203,
    //           msg: "你账号已被禁用，请联系管理员！！",
    //           req,
    //         })
    //       );
    //   }
    next();
});
process
    .on("unhandledRejection", (err, test) => {
        errLog({ err, code: 500, msg: "后端系统错误！", funName: "fatal" });
    })
    .on("uncaughtException", (err) => {
        errLog({ err, code: 500, msg: "后端系统错误！！", funName: "fatal" });
    });
server.use("/node/admin", adminRouter); //挂载用户信息路由
server.use("/node/tests", testsRouter); //挂载测试信息路由
server.use("/node/appComment", appCommentRouter); //挂载评论模块
server.use("/node/translate", translateRouter); //挂载翻译模块
server.use("/node/feedback", feedbackRouter); //挂载翻译模块
server.use("/node/brand", brandRouter); //挂载翻译模块
server.use("/node", uploadRouter); //挂载上传模块
server.use("/node/uploadPackage", uploadPackageRouter); //挂载上传模块
server.use("/node/webhook", webhookRouter); //挂载上传模块
server.use("/node/wa", waRouter);
server.use("/node/report", reportRouter);
server.use("/node/qrCode", qrCodeRouter);
server.use("/node/beauty", beautyRouter);
server.use("/node/subscriptionApiHandler", subscriptionApiHandlerRouter);
server.use("/node/iptv", iptvRouter);
server.use("/node/appVersion", appVersionHandlerRouter);
server.use("/node/appMonitor", appMonitorHandlerRouter);
server.use("/node/ai_debug", aiDebugHandlerRouter);
server.use("/node/ainote", ainoteRouter);
server.use("/node/Transir", TransirRouter);
server.use("/node/Calorie", CalorieRouter);
server.use("/node/Recipe", RecipeRouter);
server.use("/node/statistic", statisticsRouter);
server.use("/node/cohort", cohortRoutes);
console.log(String.raw`
                             _ooOoo_
                            o8888888o
                            88" . "88
                            (| -_- |)
                            O\  =  /O
                         ____/\---'\____
                       .'  \\|     |//  '.
                      /  \\|||  :  |||//  \
                     /  _||||| -:- |||||-  \
                     |   | \\\  -  /// |   |
                     | \_|  ''\---/''  |   |
                     \  .-\__  '-'  ___/-. /
                   ___'. .'  /--.--\  '. .'___
                ."" '<  '.___\_<|>_/___.' >' "".
               | | :  '- \'.;'\\ _ /';.'/ - ' : | |
               \  \ '_.   \_ __\ /__ _/   .-' /  /
           ====='-.____'.___ \_____/___.-'____.-'=====
                             '=---='

         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            佛祖保佑        永不宕机        永无BUG
`);

console.log("Node后端接口启动成功 🚀");

